package com.baizhi.aspect;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.LogDao;
import com.baizhi.entity.Admin;
import com.baizhi.entity.Log;
import com.baizhi.util.IPKit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 *
 * @Configuration  声明当前类为配置类
 * @Aspect 声明当前类为切面类 会自动的编织类中的切面和切入点
 */
@Configuration
@Slf4j
@Aspect
public class LogAspect {
   // private Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private LogDao logDao;

    /**
     * 1.写增强
     * 2.定义切入点  @annotation(com.baizhi.annotation.LogAnnotation) 切点表达式
     */
    @After("@annotation(com.baizhi.annotation.LogAnnotation)")
    public void logAfter(JoinPoint joinPoint){
        Log log1 = new Log();
//        1.日志信息的采集
        //        时间
        log1.setLogDate(new Date());
//        管理员的id 在session中有 ---》如何拿到session？---》通过request  ctrl+H  RequestContextHolder 可以获取当前请求 当前请求对应的就是当前会话的session
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        log.debug(session.toString());
        Admin admin = (Admin) session.getAttribute("admin");
        log1.setAdminId(admin.getId());

//        ip 通过工具类
        String ipAddrByRequest = IPKit.getIpAddrByRequest(request);
        if ("0:0:0:0:0:0:0:1".equals(ipAddrByRequest)){
            ipAddrByRequest = "127.0.0.1";
        }
        log1.setLogIp(ipAddrByRequest);
//            操作内容  不同的操作内容不一样---》通过方法传值？----》通过注解传值 --->通过连接点对象获取方法签名对象
//        ----》 获取方法对象 ---->得到方法的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        String value = annotation.value();
        log1.setLogContent(value);
//            操作类型
        String type = annotation.type();
        log1.setLogType(type);
        log.debug(log.toString());
//        2.日志对象添加数据库
        logDao.insertLog(log1);

    }
}
